﻿using SQLite;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using TabbedTemplate.Models;

namespace TabbedTemplate.Services
{
    public class StoreStorage : IStoreStorage
    {



        /// <summary>
        /// 用户使用过程中的Store缓存。
        /// </summary>
        public const string UserGenerateHistoryStoreDbName =
            "UserGenerateHistoryStoreDbName";

        /// <summary>
        /// 用户缓存的Store路径。
        /// </summary>
        public static readonly string UserGenerateHistoryStoreDbPath =
            Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder
                    .LocalApplicationData), UserGenerateHistoryStoreDbName);

        /// <summary>
        /// 数据库连接影子变量。
        /// </summary>
        private SQLiteAsyncConnection _userConnection;

        /// <summary>
        /// 数据库连接。
        /// </summary>
        private SQLiteAsyncConnection UserConnection =>
            _userConnection ?? (_userConnection =
                new SQLiteAsyncConnection(UserGenerateHistoryStoreDbPath));


        public StoreStorage(IPreferenceStorage preferenceStorage)
        {
            _preferenceStorage = preferenceStorage;
        }

        private IPreferenceStorage _preferenceStorage;

        /// <summary>
        /// 用户缓存店铺的数据库是否初始化了。
        /// </summary>
        /// <returns></returns>
        public bool UserCacheInitialized() => _preferenceStorage.Get(StoreStorageConstants.VersionKey, -1) ==
            StoreStorageConstants.Version;

        public async Task UserCacheInitializeAsync()
        {
            await UserConnection.CreateTableAsync<Store>();
            _preferenceStorage.Set(StoreStorageConstants.VersionKey, StoreStorageConstants.Version);
        }

        /// <summary>
        /// 在viewModel中判断空。
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public async Task<Store> GetStoreByStoreUidAsync(string uid) =>
             await UserConnection.Table<Store>()
                .FirstOrDefaultAsync(p => p.Uid == uid);

        public async Task InsertAStore(Store store) =>
            await UserConnection.InsertOrReplaceAsync(store);

        public async Task InsertAllStores(IList<Store> stores) =>
            await UserConnection.InsertOrReplaceAsync(stores);
    }
    public static class StoreStorageConstants
    {
        /// <summary>
        /// 版本。
        /// </summary>
        public const string VersionKey =
            nameof(IStoreStorage) + "." + nameof(Version);

        /// <summary>
        /// 版本。
        /// </summary>
        public const int Version = 1;
    }
}
